package service

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"patient-srv/basic/config"
	patient "patient-srv/basic/proto"
	"patient-srv/handler/model"
)

// GetHospitalDetail 获取医院详情
func (s *PatientServiceServer) GetHospitalDetail(ctx context.Context, req *patient.GetHospitalDetailReq) (*patient.GetHospitalDetailResp, error) {
	if req.HospitalId <= 0 {
		return &patient.GetHospitalDetailResp{
			Message: "医院ID无效",
		}, nil
	}

	var hospitalModel model.Hospital
	err := hospitalModel.GetByID(config.GlobalDB, uint(req.HospitalId))
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.GetHospitalDetailResp{
				Message: "医院不存在或已下线",
			}, nil
		}
		return nil, err
	}

	hospitalPB := &patient.HospitalInfo{
		Id:            int64(hospitalModel.ID),
		Name:          hospitalModel.Name,
		Logo:          hospitalModel.Logo,
		Level:         hospitalModel.Level,
		Address:       hospitalModel.Address,
		Phone:         hospitalModel.Phone,
		Introduction:  hospitalModel.Introduction,
		Route:         hospitalModel.Route,
		BusinessHours: hospitalModel.BusinessHours,
		Latitude:      hospitalModel.Latitude,
		Longitude:     hospitalModel.Longitude,
		Status:        hospitalModel.Status,
		CreatedAt:     hospitalModel.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:     hospitalModel.UpdatedAt.Format("2006-01-02 15:04:05"),
	}

	return &patient.GetHospitalDetailResp{
		Message:  "获取成功",
		Hospital: hospitalPB,
	}, nil
}

// GetHospitalList 获取医院列表
func (s *PatientServiceServer) GetHospitalList(ctx context.Context, req *patient.GetHospitalListReq) (*patient.GetHospitalListResp, error) {
	page := int(req.Page)
	pageSize := int(req.PageSize)
	offset := (page - 1) * pageSize

	var hospitals []model.Hospital
	query := config.GlobalDB.Where("status = ?", 1)

	// 支持关键词搜索
	if req.Keyword != "" {
		query = query.Where("name LIKE ?", "%"+req.Keyword+"%")
	}

	// 分页查询
	err := query.Offset(offset).Limit(pageSize).Find(&hospitals).Error
	if err != nil {
		return nil, err
	}

	// 查询总数
	var total int64
	config.GlobalDB.Model(&model.Hospital{}).Where("status = ?", 1).Where("name LIKE ?", "%"+req.Keyword+"%").Count(&total)

	// 转换为 protobuf 结构
	var hospitalPBs []*patient.HospitalInfo
	for _, h := range hospitals {
		hospitalPBs = append(hospitalPBs, &patient.HospitalInfo{
			Id:            int64(h.ID),
			Name:          h.Name,
			Logo:          h.Logo,
			Level:         h.Level,
			Address:       h.Address,
			Phone:         h.Phone,
			Introduction:  h.Introduction,
			Route:         h.Route,
			BusinessHours: h.BusinessHours,
			Latitude:      h.Latitude,
			Longitude:     h.Longitude,
			Status:        h.Status,
			CreatedAt:     h.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:     h.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &patient.GetHospitalListResp{
		Message:   "获取成功",
		Total:     total,
		Hospitals: hospitalPBs,
	}, nil
}
